<template>
  <div class="box page-miH page-bgBack p24">
    <a-layout>
      <PageHeader v-if="groupType === 'company'" @back="goBack" subTitle="返回">
        {{ "【" + detailList.name + "】" + detailList.personalPeriod }}
        {{ formType === "customer" ? "客户" : formType === "salary" ? "薪资" : formType === "social" ? "社保" : "" }}明细表
      </PageHeader>
      <PageHeader v-else @back="goBack" subTitle="返回"
        >{{ "【" + detailList.name + "】" + detailList.personalPeriod }}自定义分组</PageHeader
      >

      <div class="flex-center br8 border mt24 p24">
        <div class="border-right pr24 flex-shrink-0 mr24" style="height: 40px">
          <div class="fs18 fw500 tc-l1">合计</div>
        </div>
        <div class="flex-center overflow-x-auto flex-1">
          <div key="本月人数" class="flex-shrink-0 ph12" style="height: 60px">
            <div v-if="groupType === 'company'" class="fs14 tc-l3 fh20">
              {{ formType === "customer" ? "本月人数" : formType === "salary" ? "本月计薪人数" : "本月参保人数" }}
            </div>
            <div v-else class="fs14 tc-l3 fh20">本月人数</div>
            <div class="fs18 fw500 tc-l1 fh32 mt8">{{ detailList.empNumber ? detailList.empNumber : 0 }}人</div>
          </div>
          <template v-if="this.detailList && this.detailList.detailsAmountVOList && this.detailList.detailsAmountVOList.length > 0">
            <div v-for="item in this.detailList.detailsAmountVOList" :key="item.name" class="flex-shrink-0 ph12" style="height: 60px">
              <div class="fs14 tc-l3 fh20">{{ item.name }}</div>
              <div class="fs18 fw500 tc-l1 fh32 mt8">¥{{ item.amount || "--" }}</div>
            </div>
          </template>
        </div>
      </div>
      <div class="flex-center-between mt24">
        <div>
          <a-input-search allow-clear class="mr12" placeholder="姓名/手机号/身份证号" style="width: 180px" @search="inputChange" />
          <a-select style="width: 180px" @change="handleChange2" allowClear placeholder="员工状态">
            <!-- <a-select-option value="1">
            待入职
          </a-select-option> -->
            <a-select-option value="2"> 在职 </a-select-option>
            <a-select-option value="3"> 待离职 </a-select-option>
            <a-select-option value="4"> 离职 </a-select-option>
          </a-select>
        </div>
        <div>
          <a-button type="link" size="small" style="color: #767885; font-size: 12px" @click="reload">刷新<a-icon type="reload" /></a-button>
          <a-divider type="vertical" />
          <a-popover v-model="headVisible" title trigger="click" placement="bottom" @visibleChange="handleHeadChange">
            <div slot="content" style="width: 600px; height: 320px">
              <div>
                <div>已选择表头</div>
                <div class="overview-tag-wrapper">
                  <draggable v-model="tempSelectedHead" filter=".forbid" animation="3000" @start="onStart" @end="onEnd" :move="onMove">
                    <transition-group>
                      <a-tag
                        v-for="(item, index) in tempSelectedHead"
                        :key="index"
                        :closable="item.title !== '姓名' && item.title !== '身份证号'"
                        :color="item.title !== '姓名' && item.title !== '身份证号' ? '#fff' : '#E8E8E8'"
                        :class="
                          item.title !== '姓名' && item.title !== '身份证号' ? 'overview-select-tag' : 'overview-select-tag-name forbid'
                        "
                        @close="deleteSelectedHead($event, index)"
                        >{{ item.title }}</a-tag
                      >
                    </transition-group>
                  </draggable>
                </div>
              </div>
              <div>
                <div>可选择表头</div>
                <div>
                  <a-tag
                    v-for="(item, index) in tempNoSelectedHead"
                    :key="index"
                    class="overview-no-select-tag"
                    @click="addSelectedHead(index)"
                    >{{ item.title }}</a-tag
                  >
                </div>
              </div>
              <a-row type="flex" justify="end" style="position: absolute; bottom: 20px; right: 20px">
                <a-button style="margin-right: 12px" @click="handleHeadCancel">取消</a-button>
                <a-button type="primary" @click="handleHeadSearch">查询</a-button>
              </a-row>
            </div>
            <a-button type="link" size="small" style="color: #767885; font-size: 12px">选择表头<a-icon type="menu" /></a-button>
          </a-popover>
          <a-divider type="vertical" />
          <a-dropdown>
            <a-menu slot="overlay" @click="download">
              <a-menu-item key="8" :disabled="!dataList.length">全部导出</a-menu-item>
            </a-menu>
            <a-button type="link" size="small" style="color: #767885; font-size: 12px">导出<a-icon type="caret-down" /></a-button>
          </a-dropdown>
        </div>
      </div>
      <div class="mt24">
        <a-table
          :loading="loading"
          :columns="columns"
          :data-source="dataList"
          :pagination="pagination"
          rowKey="id"
          :scroll="{ x: 1200 }"
          @change="handleTableChange"
        />
      </div>
    </a-layout>
  </div>
</template>
<script>
import { getDetailsReqNew, updateAutoTaxGrand, getSelectHeadersReqNew, updateHead } from "./api";
import draggable from "vuedraggable";
import ExportMixin from "xqjr-plugin-common/UploadOrExport/exportMixin";
import { initColumns } from "./funcs";
import axios from "axios";

const mixin = new ExportMixin();
export default {
  mixins: [mixin],
  components: { draggable },
  data() {
    return {
      tempSelectedHead: [],
      tempNoSelectedHead: [],
      headVisible: false,
      title: "",
      buttonState: true,
      inputName: null,
      selectedRowId: [],
      selectedRowKeys: [],
      loading: false,
      dataList: [],
      initColumns,
      columns: [],
      detailList: [],
      empStatus: null,
      selectString: {},
      monthly: 5,
      yearly: 2021,
      bankType: undefined,
      formType: "",
      groupType: "",
      pagination: {
        pageSize: 10,
        total: 0,
        size: "default",
        current: 1,
        showTotal: (total) => `共 ${total} 条`,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ["10", "20", "50", "100"]
      }
    };
  },
  created() {
    this.detailList = JSON.parse(localStorage.getItem("kehumingxibiao_item"));

    console.log(this.detailList);

    this.monthly = this.$route.query.monthly;
    this.yearly = this.$route.query.yearly;
    this.formType = this.$route.query.formType;
    this.groupType = this.$route.query.groupType;

    this.getSelectHeaders();
    this.getDetailsList();
  },
  methods: {
    reload() {
      this.getDetailsList();
      this.$notification["success"]({
        message: "成功",
        description: "刷新成功"
      });
    },
    getSelectHeaders() {
      getSelectHeadersReqNew({
        id: this.detailList.subjectId,
        type: this.detailList.subjectType,
        customerDetailsIdList: this.detailList.customerDetailsIds,
        monthly: this.monthly,
        yearly: this.yearly
      }).then((res) => {
        var arr = [];
        this.selectString = res.data;
        this.tempSelectedHead = [];
        arr = JSON.parse(JSON.stringify(res.data.canSee));
        const tempArr = [];
        arr.forEach((item) => {
          if (item.fieldEnName === "empName" || item.fieldEnName === "idCard") {
            tempArr.push({
              title: item.fieldName,
              dataIndex: item.fieldEnName,
              width: item.fieldName === "身份证号" ? 200 : 130,
              fixed: item.fieldName === "姓名" || item.fieldName === "身份证号" ? "left" : null,
              fieldName: item.fieldName,
              fieldEnName: item.fieldEnName,
              isEdit: item.isEdit
            });
          } else {
            tempArr.push({
              title: item.fieldName,
              dataIndex: item.fieldName,
              width: 130,
              fieldName: item.fieldName,
              fieldEnName: item.fieldEnName,
              isEdit: item.isEdit
            });
          }
        });
        this.tempSelectedHead = tempArr;
        this.columns = JSON.parse(JSON.stringify(this.tempSelectedHead));
        var arr2 = [];
        this.tempNoSelectedHead = [];
        arr2 = JSON.parse(JSON.stringify(res.data.ignore));
        const tempArr2 = [];
        arr2.forEach((item, index) => {
          if (item.fieldEnName === "empName" || item.fieldEnName === "idCard") {
            tempArr2.push({
              title: item.fieldName,
              dataIndex: item.fieldEnName,
              fieldName: item.fieldName,
              fieldEnName: item.fieldEnName,
              isEdit: item.isEdit
            });
          } else {
            tempArr2.push({
              title: item.fieldName,
              dataIndex: item.fieldName,
              fieldName: item.fieldName,
              fieldEnName: item.fieldEnName,
              isEdit: item.isEdit
            });
          }
        });
        this.tempNoSelectedHead = tempArr2;
      });
    },
    handleHeadSearch() {
      this.selectString.canSee = this.tempSelectedHead;
      this.selectString.ignore = this.tempNoSelectedHead;
      updateHead(this.selectString).then((res) => {
        this.getSelectHeaders();
        this.headVisible = false;
      });
    },
    handleHeadChange(visible) {
      if (visible === false) {
        this.tempSelectedHead = JSON.parse(JSON.stringify(this.selectedHead));
        this.tempNoSelectedHead = JSON.parse(JSON.stringify(this.noSelectedHead));
      }
    },
    addSelectedHead(index) {
      const temp = JSON.parse(JSON.stringify(this.tempNoSelectedHead[index]));
      this.tempNoSelectedHead.splice(index, 1);
      this.tempSelectedHead.push(temp);
    },
    deleteSelectedHead(e, index) {
      e.preventDefault();
      const temp = JSON.parse(JSON.stringify(this.tempSelectedHead[index]));
      this.tempSelectedHead.splice(index, 1);
      this.tempNoSelectedHead.push(temp);
    },
    handleHeadCancel() {
      this.headVisible = false;
      this.tempSelectedHead = JSON.parse(JSON.stringify(this.selectedHead));
      this.tempNoSelectedHead = JSON.parse(JSON.stringify(this.noSelectedHead));
    },
    onStart() {
      this.drag = true;
    },
    onEnd() {
      this.drag = false;
    },

    onMove(e) {
      if (e.relatedContext.element.title === "姓名" || e.relatedContext.element.title === "身份证号") return false;
      return true;
    },
    autoAdd() {
      updateAutoTaxGrand({
        monthly: this.monthly,
        yearly: this.yearly,
        companyId: this.detailList.companyId,
        companyName: this.detailList.name,
        unpaidAmount: this.detailList.customerFees
      }).then((res) => {
        this.addVisible = false;
        this.$notification["success"]({
          message: "success",
          description: "生成成功"
        });
      });
    },
    onSelectChange(selectedRowKeys, selectedRow) {
      this.selectedRowId = [];
      this.selectedRowKeys = selectedRowKeys;
      if (this.selectedRowKeys.length) {
        this.buttonState = false;
      } else {
        this.buttonState = true;
      }
      selectedRow.forEach((item, index) => {
        this.selectedRowId.push(item.id);
      });
    },
    getDetailsList() {
      this.loading = true;
      getDetailsReqNew({
        empStatus: this.empStatus,
        id: this.detailList.subjectId,
        type: this.detailList.type,
        customerDetailsIdList: this.detailList.customerDetailsIds,
        nameOrPhoneOrIdCard: this.inputName,
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize,
        monthly: this.monthly,
        yearly: this.yearly
      }).then((res) => {
        this.loading = false;
        this.dataList = res.data.entities.map((item) => {
          const newItem = { ...item };
          if (item.detailsAmountVOList && item.detailsAmountVOList.length > 0) {
            for (let i = 0; i < item.detailsAmountVOList.length; i++) {
              const temp = item.detailsAmountVOList[i];
              newItem[temp.name] = temp.amount;
            }
          }
          return newItem;
        });
        this.pagination.total = res.data.entityCount; // 共多少条
      });
    },
    handleChange2(e) {
      this.pagination.current = 1;
      this.pagination.pageSize = 10;
      this.empStatus = e;
      this.getDetailsList();
    },
    // 返回
    goBack() {
      this.$router.go(-1);
    },
    // 导出
    download() {
      axios({
        url: `/hr/api/v1/customerDetailsNew/exportNew`,
        method: "post",
        data: {
          id: this.detailList.subjectId,
          type: this.groupType,
          customerDetailsIdList: this.detailList.customerDetailsIds,
          monthly: this.monthly,
          yearly: this.yearly
        },
        responseType: "blob",
        headers: {
          token: this.token
        }
      })
        .then((res) => {
          if (res.data && res.data.type === "application/json") {
            const reader = new FileReader();
            reader.readAsText(res.data, "utf-8");
            reader.onload = () => {
              const resJson = JSON.parse(reader.result);
              this.$message.error(resJson.msg);
            };
          } else {
            const blob = new Blob([res.data], {
              type: "application/octet-stream"
            });
            const link = document.createElement("a");
            link.download = `${this.detailList.name + this.detailList.personalPeriod}_` + "客户明细表导出详情" + ".xlsx";
            link.href = URL.createObjectURL(blob);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
          }
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    inputChange(e) {
      this.inputName = e;
      this.pagination.current = 1;
      this.pagination.pageSize = 10;
      this.getDetailsList();
    },
    // 分页
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.getDetailsList();
    }
  }
};
</script>
<style lang="scss" scoped>
$body-width: calc(100% - 338px);

.overview-no-select-tag {
  background-color: #fff;
  cursor: pointer;
  margin: 5px;
}
.overview-tag-wrapper {
  ::v-deep .ant-tag {
    .anticon-close {
      color: var(--primary);
    }
  }
}
.overview-tag-wrapper {
  ::v-deep .ant-tag {
    .anticon-close {
      color: var(--primary);
    }
  }
}
.overview-select-tag-name {
  cursor: pointer;
  margin: 5px;
  color: #666666;
}
.overview-select-tag {
  background-color: #fff !important;
  color: var(--primary) !important;
  border: 1px solid var(--primary);
  cursor: pointer;
  margin: 5px;
}
</style>
